<script setup lang="ts">
import { ref } from 'vue'
import XtxSwiper from '@/components/XtxSwiper.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import { getHomeBannerApi, getHomeCategoryAPI, getHotPanelAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from './components/PageSkeleton.vue'
import { useGuessList } from '@/composables'
// 轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerApi()
  // console.log(res)
  bannerList.value = res.result
}
// 分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  // console.log(res)
  categoryList.value = res.result
}
// 热门推荐数据
const hotPanelList = ref<HotItem[]>([])
const getHotPanelData = async () => {
  const res = await getHotPanelAPI()
  // console.log(res)
  hotPanelList.value = res.result
}
const isLoading = ref(false)

// 进入页面获取banner数据
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHotPanelData()])
  isLoading.value = false
})
// 两种实现方式
// const guessRef = ref<XtxGuessInstance>()
// const onScrolltolower = () => {
//   // 触底加载数据
//   guessRef.value?.getMore()
// }
const { guessRef, onScrolltolower } = useGuessList()

// 是否展示下拉刷新动画
const isTriggered = ref(false)
// 下拉刷新调用
const onRefresherrefresh = async () => {
  isTriggered.value = true
  guessRef.value.resetData() //加载数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHotPanelData(),
    guessRef.value?.getMore(),
  ])

  isTriggered.value = false
}
</script>

<template>
  <!-- 导航栏 -->
  <CustomNavbar />
  <PageSkeleton v-if="isLoading" />
  <scroll-view
    v-else
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    class="scroll-view"
    scroll-y
    @scrolltolower="onScrolltolower"
  >
    <!-- 轮播图 -->
    <XtxSwiper :list="bannerList" />
    <!-- 分类面板 -->
    <CategoryPanel :list="categoryList" />
    <!-- 热门推荐 -->
    <HotPanel :list="hotPanelList" />
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessRef" />
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
